function reltarget = relfilename(sourcefile, targetfile)
% relfilename  - build relative filename from two given files
%
% FORMAT:       rfname = relfilename(sourcefile, targetfile)
%
% Input fields:
%
%       sourcefile  relative filename of the originating file
%       targetfile  relative filename of the target file
%
% Output fields:
%
%       rfname      relative filename between the two
%
% relfilename is useful to build relative filenames for HTML
% compliant links between documents in a folder tree

% Version:  v0.7a
% Build:    7081516
% Date:     Aug-15 2007, 4:35 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
   ~ischar(sourcefile) || ...
   ~ischar(targetfile)
    error( ...
        'BVQXtools:BadArgument',...
        'Bad or missing argument.' ...
    );
end

% for empty target file use source dir
if isempty(targetfile)
    [reltarget{1:3}] = fileparts(sourcefile);
    reltarget = [reltarget{2:3}];
    return;
end

% accept empty sourcefile
if isempty(sourcefile)
    sourcefile = 'CURRENT.DIR';
else
    sourcefile = strrep(sourcefile(:)', '\', '/');
end
targetfile = strrep(targetfile(:)', '\', '/');

% get filename parts
schain = splittocell(sourcefile, '/', 1);
tchain = splittocell(targetfile, '/', 1);

% test for ms-dos names
if length(schain) > 1 && ...
    length(tchain) > 1 && ...
   (any(schain{1} == ':') || ...
    any(tchain{1} == ':'))
    if any(tchain{1} == ':')
        if strcmp(schain{1}, tchain{1}) || ...
           (ispc && ...
            strcmpi(schain{1}, tchain{1}))
            schain(1) = [];
            tchain(1) = [];
        else
            reltarget = targetfile;
            return;
        end
    elseif targetfile(1) == '/'
        reltarget = [schain{1} targetfile]; return;
    else
        reltarget = [gluetostring({schain{1:(end-1)}}, '/') '/' ...
                     targetfile];
        return;
    end
else
    if targetfile(1) == '/'
        reltarget = targetfile;
        return;
    elseif sourcefile(1) == '/'
        reltarget = [gluetostring({schain{1:(end-1)}}, '/') '/' ...
                     targetfile];
        return;
    end
end

% remove all leading similarities
while length(schain) > 0 && ...
    length(tchain) > 0 && ...
    (strcmp(schain{1}, tchain{1}) || ...
     (ispc && ...
      strcmpi(schain{1}, tchain{1})))
    schain(1) = [];
    tchain(1) = [];
end

% initialize reltarget
reltarget = '';

% for each remaining folder name go one dir up
while length(schain) > 1
    reltarget = ['../' reltarget];
    schain(1) = [];
end

% add remaining folders and file from target
reltarget = [reltarget gluetostring(tchain, '/')];
